package com.tandashi.springbootstudy01.intercept;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Order(0)
@Slf4j
public class CostTimeInterceptor {

    //@within 对象级别 @annotation 方法级别
    @Pointcut("@within(com.tandashi.springbootstudy01.intercept.CostTime) || @annotation(com.tandashi.springbootstudy01.intercept.CostTime)")
    public void costTime() {

    }

    @Around("costTime()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long time = System.currentTimeMillis() - start;

        if (time > 200L) {
            try {
                String clazzName = joinPoint.getTarget().getClass().getSimpleName();
                String methodName = joinPoint.getSignature().getName();
                String args = objectMapper.writeValueAsString(joinPoint.getArgs());
                args = args.substring(1, args.length() - 1);
                log.error("{}.{}({}) - {} ms",clazzName,methodName,args,time);
            } catch (Throwable ignore) {
            }
        }

        return result;
    }

    @Autowired
    private ObjectMapper objectMapper;

}
